package idv.kikka.server.handler;

import idv.kikka.server.common.R;
import idv.kikka.server.service.factories.ChatGroupServiceFactory;
import idv.kikka.server.entity.ChatGroup;
import idv.kikka.common.message.GroupQuitRequestMessage;
import idv.kikka.common.message.GroupQuitResponseMessage;
import idv.kikka.server.service.ChatGroupService;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

@ChannelHandler.Sharable
public class GroupQuitRequestMessageHandler extends SimpleChannelInboundHandler<GroupQuitRequestMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, GroupQuitRequestMessage msg) throws Exception {
        String groupName = msg.getGroupName();
        String username = msg.getUsername();
        ChatGroupService chatGroupService= ChatGroupServiceFactory.getChatGroupService();
        R<ChatGroup> result = chatGroupService.removeMember(groupName, username);
        if(result.getCode()!=1){
            ctx.channel().writeAndFlush(new GroupQuitResponseMessage(false, result.getMsg()));
        }
        else {
            ctx.channel().writeAndFlush(new GroupQuitResponseMessage(true,groupName+"已退出！"));
        }
    }
}
